<template>
  <div class="map-wrapper">
    <div id="panel"></div>
    <div class="toggle-buttons">
      <el-button @click="toggleSearchBar" class="toggle-button">搜索框</el-button>
      <el-button @click="toggleDrawArea" class="toggle-button">绘制区域</el-button>
      <el-button @click="toggleRouteInfo" class="toggle-button">路线</el-button>
    </div>
    <div class="search-bar" v-if="showSearchBar">
      <el-input v-model="searchText" placeholder="请输入搜索关键字" id="searchInputId" class="search-input"/>
      <el-input v-model="startName" placeholder="起始地点" class="search-input"></el-input>
      <el-input id="end" v-model="endName" placeholder="目的地点" class="search-input"></el-input>
      <el-select v-model="rule" class="search-input">
        <el-option
            v-for="item in routeRules"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            placeholder="请选择驾车算路策略"
        />
      </el-select>
      <el-select v-model="selectedLanguage" class="search-input">
        <el-option
          v-for="lang in languages"
          :key="lang.value"
          :label="lang.label"
          :value="lang.value"
        />
      </el-select>
      <el-button @click="goView" class="search-button">搜索</el-button>
      <el-button @click="speakRoute" class="search-button">播报路线</el-button>
    </div>
    <div class="route-info" v-if="showRouteInfo && routeArr.length > 0">
      <div class="route-policy">路线规划策略： {{policy}}</div>
      <div class="route-distance">总距离： {{(distance / 1000).toFixed(2)}} 公里</div>
      <div class="route-duration">总时间： {{ formatDuration(duration) }}</div>
      <el-row
        v-for="(item, index) in routeArr"
        :key="index"
        class="route-step"
      >
        {{item.instruction}}
      </el-row>
    </div>
    <div id="amap"></div>
    <div class="draw-area" v-if="showDrawArea">
      <div class="select">
        <div style="margin: 10px 0">
          <el-button @click="drawOther">绘制多边形</el-button>
          <el-button @click="drawRect">绘制矩形</el-button>
          <el-button @click="drawCircle">绘制圆形</el-button>
          <el-button @click="stopDrawAndClear()">清除</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import logo from "@/assets/vue.svg";

window._AMapSecurityConfig = {
  securityJsCode: "fc2ea34c3880e566ed95dd7da7d0305e",
};

let map: any = null;
let placeSearch,
  AMapObj: any,
  geocoder: { getAddress: (arg0: any, arg1: (status: any, result: any) => void) => void; };
let mouseTool: any = null;
let circleId = 1;
let auto = ref("");
let autoOptions = {
  input: "searchInputId",
};
let searchText = ref("");
let startName = ref("");
let endName = ref("");
let rule = ref("");
const routeRules = [
  {
    value: 0,
    label: "速度优先",
  },
  {
    value: 1,
    label: "费用优先",
  },
  {
    value: 2,
    label: "距离优先",
  },
  {
    value: 41,
    label: "躲避拥堵＋少收费",
  },
  {
    value: 32,
    label: "默认",
  },
];

let routeArr = ref([]);
let policy = ref("");
let distance = ref(0);
let duration = ref(0);

let showSearchBar = ref(true);
let showDrawArea = ref(true);
let showRouteInfo = ref(true);

const languages = [
  { value: "en-US", label: "English" },
  { value: "zh-CN", label: "中文" },
  { value: "es-ES", label: "Español" },
  // 添加更多语言选项
];

let selectedLanguage = ref("en-US");

const toggleSearchBar = () => {
  showSearchBar.value = !showSearchBar.value;
};

const toggleDrawArea = () => {
  showDrawArea.value = !showDrawArea.value;
};

const toggleRouteInfo = () => {
  showRouteInfo.value = !showRouteInfo.value;
};

onMounted(() => {
  initMap();
});

async function initMap() {
  await AMapLoader.load({
    key: "f7cc6f7d59f4f75b40c48e29149af28e",
    version: "2.0",
    plugins: [
      "AMap.ToolBar",
      "AMap.Scale",
      "AMap.Geolocation",
      "AMap.PlaceSearch",
      "AMap.Geocoder",
      "AMap.HawkEye",
      "AMap.MapType",
      "AMap.CircleEditor",
      "AMap.MouseTool",
      "AMap.AutoComplete",
      "AMap.PlaceSearch",
      "AMap.Driving",
    ],
  }).then((AMap) => {
    AMapObj = AMap;
    map = new AMap.Map("amap", {
      zoom: 12,
      resizeEnable: true,
      center: [116.51767, 40.009007],
      viewMode: "3D",
    });
    const mapType = new AMap.MapType();
    const hawkEye = new AMap.HawkEye();
    const toolbar = new AMap.ToolBar({
      position: "LT",
    });
    const scale = new AMap.Scale();
    const geolocation = new AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 0,
      convert: true,
      showButton: true,
      buttonPosition: "LB",
      buttonOffset: new AMap.Pixel(10, 20),
      showMarker: true,
      showCircle: true,
      panToLocation: true,
      zoomToAccuracy: true,
    });
    geocoder = new AMap.Geocoder({
      city: "全国",
    });
    map.addControl(geolocation);
    map.addControl(toolbar);
    map.addControl(scale);
    map.addControl(hawkEye);
    map.addControl(mapType);

    poiSearch();

    bindEvent();

    createMarker();

    mouseTool = new AMap.MouseTool(map);
  });
}

const poiSearch = () => {
  auto.value = new AMapObj.AutoComplete(autoOptions);
  const placeSearch = new AMapObj.PlaceSearch({
    map: map,
    city: "",
    pageSize: 5,
    pageIndex: 1,
    citylimit: false,
    autoFitView: true,
    panel: "panel",
  });
  auto.value.on("select", function (e) {
    placeSearch.search(e.poi.name);
  });
};

const doubleClick = (e) => {
  console.log("您在 [ " + e.lnglat.getLng() + "," + e.lnglat.getLat() + " ] 的位置双击了地图！");
  const x = e.lnglat.getLng();
  const y = e.lnglat.getLat();
  showInfo(e, x, y);
};

const showInfoMove = () => {
  console.log("您移动了您的鼠标！");
};

const signClick = (e) => {
  console.log("您在 [ " + e.lnglat.getLng() + "," + e.lnglat.getLat() + " ] 的位置单击了地图！");
  const x = e.lnglat.getLng();
  const y = e.lnglat.getLat();
  showInfo(e, x, y);
};

const bindEvent = () => {
  console.log("事件绑定成功");
  map.on("click", signClick);
};

const showInfo = (e: any, x: any, y: any) => {
  geocoder.getAddress(e.lnglat, (status, result) => {
    if (status === "complete" && result.regeocode) {
      const address = result.regeocode.formattedAddress;
      const infoContent = `
        <div style="padding:7px 0px 0px 0px;">
          <div class="global-header">当前位置</div>
          <p class='input-item'>经度: ${x}</p>
          <p class='input-item'>纬度: ${y}</p>
          <p class='input-item'>地址: ${address}</p>
          <img src="${logo}" alt="Vue Logo" width="100px;height=100px"/>
        </div>
      `;
      const infoWindow = new AMapObj.InfoWindow({
        content: infoContent,
      });
      infoWindow.open(map, new AMapObj.LngLat(x, y));
    } else {
      console.error("获取地址失败");
    }
  });
};

const createMarker = () => {
  const markerContent = `
      <div class="custom-content-marker">
            <img src="//a.amap.com/jsapi_demos/static/demo-center/icons/dir-via-marker.png">
            <div class="close-btn">X</div>
          </div>`;
  const position = new AMapObj.LngLat(103.841856, 36.053549);
  const marker = new AMapObj.Marker({
    position: position,
    content: markerContent,
    offset: new AMapObj.Pixel(-13, -30),
  });
  map.add(marker);
  const closeBtn = document.querySelector(".close-btn");
  if (closeBtn) {
    closeBtn.addEventListener("click", () => {
      clearMarker(marker);
    });
  }
};

const clearMarker = (marker: any) => {
  console.log("移除点标记");
  map.remove(marker);
};

const drawRect = () => {
  console.log("绘制矩形");
  mouseTool.rectangle({
    strokeColor: "red",
    strokeOpacity: 0.5,
    strokeWeight: 2,
    fillColor: "blue",
    fillOpacity: 0.2,
    strokeStyle: "solid",
  });
};

const drawCircle = () => {
  console.log("绘制圆形");
  mouseTool.circle({
    strokeColor: "#FF33FF",
    strokeOpacity: 1,
    strokeWeight: 6,
    strokeOpacity: 0.2,
    fillColor: "#1791fc",
    fillOpacity: 0.4,
    strokeStyle: "dashed",
    strokeDasharray: [30, 10],
  });
};

const drawOther = () => {
  mouseTool.polygon({
    strokeColor: "#FF33FF",
    strokeOpacity: 1,
    strokeWeight: 4,
    strokeOpacity: 0.2,
    fillColor: "#1791fc",
    fillOpacity: 0.2,
    strokeStyle: "solid",
  });
};

const stopDrawAndClear = () => {
  mouseTool.close(true);
};

const goView = () => {
  const driving = new AMapObj.Driving({
    map,
    policy: rule.value,
  });
  const points = [
    { keyword: startName.value, city: "北京" },
    { keyword: endName.value, city: "兰州" },
  ];

  driving.search(points, (status, result) => {
    if (status === "complete") {
      routeArr.value = result.routes[0].steps;
      policy.value = result.routes[0].policy;
      distance.value = result.routes[0].distance; // 提取距离
      duration.value = result.routes[0].time; // 提取时间
    }
  });
};

const formatDuration = (durationInSeconds) => {
  const days = Math.floor(durationInSeconds / (24 * 3600));
  const hours = Math.floor((durationInSeconds % (24 * 3600)) / 3600);
  const minutes = Math.floor((durationInSeconds % 3600) / 60);
  return `${days}天 ${hours}小时 ${minutes}分钟`;
};

const speakRoute = () => {
  const speech = new SpeechSynthesisUtterance();
  speech.lang = selectedLanguage.value;
  speech.text = routeArr.value.map((step) => step.instruction).join(". ");
  window.speechSynthesis.speak(speech);
};

onUnmounted(() => {
  map?.destroy();
});
</script>

<style scoped lang="less">
.map-wrapper {
  #amap {
    width: 100%;
    height: 100vh;
  }
}

#panel {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 999;
}

.toggle-buttons {
  position: absolute;
  top: 10px;
  left: 50px;
  z-index: 1000;
  display: flex;
  gap: -0px;
}

.toggle-button {
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 0 10px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.toggle-button:hover {
  background-color: #66b1ff;
}

.search-bar {
  position: absolute;
  top: 60px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 999;
  display: flex;
  gap: 10px;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  flex-wrap: wrap;
}

.search-input {
  flex: 1;
  min-width: 150px;
}

.search-button {
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 0 20px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.search-button:hover {
  background-color: #66b1ff;
}

.route-info {
  position: absolute;
  top: 100px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 9999;
  border: 1px solid springgreen;
  background-color: white;
  padding: 10px;
  max-height: 50vh;
  overflow-y: auto;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.route-policy {
  font-weight: bold;
  margin-bottom: 10px;
}

.route-distance {
  margin-bottom: 10px;
}

.route-duration {
  margin-bottom: 10px;
}

.route-step {
  padding: 5px 0;
  border-bottom: 1px solid #eee;
}

.draw-area {
  position: absolute;
  bottom: 10px;
  right: 10px;
  display: flex;
  justify-content: center;
  .select {
    background-color: white;
    padding: 0 10px;
    margin-right: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  }
  .action {
    display: flex;
    align-items: center;
  }
}

@media (max-width: 768px) {
  .map-wrapper {
    .search-bar {
      top: 60px;
      left: 10px;
      right: 10px;
      transform: none;
      flex-direction: column;
      gap: 10px;
    }

    .route-info {
      top: 100px;
      left: 10px;
      right: 10px;
      transform: none;
      max-height: 50vh;
      overflow-y: auto;
    }

    .draw-area {
      bottom: 10px;
      right: 10px;
      flex-direction: column;
      gap: 10px;
    }
  }
}
</style>
